package com.cjq.allservice.service.impl;

import com.cjq.allservice.entity.Type;
import com.cjq.allservice.mapper.TypeMapper;
import com.cjq.allservice.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cjq
 * @since 2022-01-11
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Override
    public List<Type> listWithTree() {

        List<Type> list = baseMapper.selectList(null);
        List<Type> firstType = list.stream().filter(type ->
             type.getTypeParentId().equals("0")
        ).map((menu)->{
            menu.setChildren(getChildren(menu,list));
            return menu;
        }).collect(Collectors.toList());
        return firstType;

    }

    //递归查找所有菜单的子菜单
    private List<Type> getChildren(Type root,List<Type> types){
        List<Type> collect = types.stream().filter((type) -> {
            return type.getTypeParentId().equals(root.getTypeId());
        }).map(type -> {
            type.setChildren(getChildren(type,types));
            return type;
        }).collect(Collectors.toList());
        return collect;
    }
}
